import {getInfo, login, logout} from "@/api/login.js";
import {getToken, removeToken, setToken} from "@/utils/token.js";
import DEFAVA from '@/assets/image/def_ava.jpg'

export const useUserStore = defineStore(
    'user',
    {
        state: () => ({
            token: getToken(),
            id: '',
            name: '',
            avatar: '',
            roles: [],
            permissions: [],
        }),
        actions: {
            //登录
            login(loginForm) {
                return new Promise((resolve, reject) => {
                    login(loginForm).then(res => {
                        setToken(res.data?.token ?? res.data)
                        resolve(res);
                    }).catch(error => {
                        reject(error);
                    })
                })
            },
            getInfo(){
                return new Promise((resolve, reject) => {
                    getInfo().then(res => {
                        const user = res.data.user
                        if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                            this.roles = res.data.roles
                            this.permissions = res.data.permissions
                        } else {
                            this.roles = ['ROLE_DEFAULT']
                        }
                        this.id = user.userId
                        this.name = user.userName
                        this.avatar = (user.avatar === "" || user.avatar === null) ? DEFAVA : user.avatar
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            logOut(){
                return new Promise((resolve, reject) => {
                    logout(this.token).then(() => {
                        this.$reset()
                        removeToken()
                        resolve()
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
        }
    }
)

